﻿using System;
using System.Linq;
using System.Web.Http.Filters;
using Se.Framework.Common;
using Se.Framework.Common.Data;

namespace Se.Framework.Web.Mvc.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class UnitOfWorkManagementFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception == null)
            {
                var attr = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<UnitOfWorkPropertiesAttribute>().FirstOrDefault();
                if (attr == null || attr.AutoCommitEnable)
                {
                    ObjectRegistry.Current.Resolve<IUnitOfWork>().Commit();
                }
            }
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}
